package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    @Autowired
    SpuDetailService spuDetailService;
    @Autowired
    SpuService spuService;
    @Override
    public SpuDetailDTO querySpuDetailById(Long skuid) {
        //1.获取 spuid
        Long spuId = getById(skuid).getSpuId();
        //2.查询detail
        SpuDetail spuDetail = spuDetailService.getById(spuId);
        return new SpuDetailDTO(spuDetail);
    }

    @Override
    @Transactional
    public void updateSkuByskuId(Long skuID, Integer num) {
        Sku sku = getById(skuID);
        boolean success = update().eq("id", skuID).set("stock", sku.getStock() - num).update();
        if (!success) {
            throw new LyException("减库存失败", 500);
        }
    }

    @Override
    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        //1.0 查询 并判断
        List<Sku> skuList = query().eq("spu_id", spuId).list();
        if (skuList==null) {
            throw new LyException("spuID下没有sku", 204);
        }
        return SkuDTO.convertEntityList(skuList);
    }
}
